// https://www.lintcode.com/problem/island-perimeter/

public class Solution {
    /**
     * @param grid: a 2D array
     * @return: the perimeter of the island
     */
    public int islandPerimeter(int[][] grid) {
        // Write your code here
        int ret = 0;
        if (grid.length > 0) {
            for (int i = 0; i < grid.length; ++i) {
                for (int j = 0; j < grid[0].length; ++j) {
                    if (grid[i][j] != 0) {
                        ret += 4; // 周长最大为4
                        // 左边有陆地，减2.两块陆地各减1。
                        if ((i > 0) && (grid[i - 1][j] == 1)) {
                            ret -= 2;
                        }
                        // 上边有陆地，减2.两块陆地各减1。
                        if ((j > 0) && (grid[i][j - 1] == 1)) {
                            ret -= 2;
                        }
                    }
                }
            }
        }
        return ret;
    }
}